package cn.yuanqiao.archive.danganzhengli.utils;

import org.jamel.dbf.DbfReader;
import org.jamel.dbf.structure.DbfRow;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DBFReadUtils {

    public static List<Map<String, String>> parseDBFTitle(File dbfFile) throws Exception{
        List<Map<String, String>> dataList = new ArrayList<>();
        try (DbfReader reader = new DbfReader(dbfFile)) {
            int numberOfColumns = reader.getHeader().getFieldsCount();
            for(int i =0;i<numberOfColumns;i++){
                Map<String, String> map = new HashMap<>();
                map.put("num",String.valueOf(i));
                map.put("name",reader.getHeader().getField(i).getName());
                dataList.add(map);
            }
        } catch (Exception e) {
            throw e;
        }
        return dataList;
    }

    public static List<Map<Integer, String>> parseDBF(File dbfFile) throws Exception{
        List<Map<Integer, String>> data = new ArrayList<>();
        try (DbfReader reader = new DbfReader(dbfFile)) {
            int numberOfColumns = reader.getHeader().getFieldsCount();
            DbfRow row = null;
            while ((row = reader.nextRow()) != null) {
                Map<Integer, String> rowData = new HashMap<>();
                for (int i = 0; i < numberOfColumns; i++) {
                    rowData.put(i, row.getString(reader.getHeader().getField(i).getName()));
                }
                data.add(rowData);
            }
        } catch (Exception e) {
            throw e;
        }
        return data;
    }

    public static void main(String[] args) throws Exception {
        //Map<String, String> map = parseDBFTitle(new File("C:\\Users\\Administrator\\Desktop\\工作簿1.dbf"));
        List<Map<Integer, String>> map = parseDBF(new File("C:\\Users\\Administrator\\Desktop\\工作簿1.dbf"));
        System.out.println(map);

    }
}
